package com.zbkj.service.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.dal.base.constants.TaskConstants;
import com.zbkj.dal.base.enums.DuesStatusEnums;
import com.zbkj.dal.common.utils.RedisUtil;
import com.zbkj.dal.dao.DuesOrderMapper;
import com.zbkj.dal.entity.order.DuesOrder;
import com.zbkj.service.service.QuotaTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
@Service
public class QuotaTaskServiceImpl implements QuotaTaskService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private DuesOrderMapper duesOrderMapper;

    @Value("${quota.recharge.auto.cancel.time:15}")
    private Long quotaRechargeAutoCancelTime;

    @Override
    public void quotaAutoCancel() {
        String redisKey = TaskConstants.QUOTA_RECHARGE_TASK_REDIS_KEY_AUTO_CANCEL_KEY;
        Long size = redisUtil.getListSize(redisKey);
        log.info("QuotaTaskServiceImpl.quotaAutoCancel | size:" + size);
        if (size < 1) {
            return;
        }
        for (int i = 0; i < size; i++) {
            //如果10秒钟拿不到一个数据，那么退出循环
            Object data = redisUtil.getRightPop(redisKey, 10L);
            if (ObjectUtil.isNull(data)) {
                continue;
            }
            String orderNo = String.valueOf(data);
            try {
                boolean result = orderAutoCancel(orderNo);
                if (!result) {
                    redisUtil.lPush(redisKey, data);
                }
            } catch (Exception e) {
                log.error("QuotaTaskServiceImpl.quotaAutoCancel-{} | fail:", orderNo, e);
                redisUtil.lPush(redisKey, data);
            }
        }
    }

    public boolean orderAutoCancel(String orderNo) {
        LambdaQueryWrapper<DuesOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DuesOrder::getOrderNo, orderNo);
        DuesOrder duesOrder = duesOrderMapper.selectOne(wrapper);
        if (Objects.isNull(duesOrder)) {
            log.error("自动取消额度认购订单，订单不存在，订单号为:{}", orderNo);
            return true;
        }
        if (Objects.equals(duesOrder.getPaid(), DuesStatusEnums.PAID.getCode())) {
            return true;
        }

        if (Objects.equals(duesOrder.getPaid(), DuesStatusEnums.CANCEL.getCode())) {
            return true;
        }
        LocalDateTime cancelTimme = duesOrder.getCreateTime().plusMinutes(quotaRechargeAutoCancelTime);
        if (LocalDateTime.now().isBefore(cancelTimme)) {
            return false;
        }
        // 如果已超时，且未支付，则取消订单
        duesOrder.setPaid(DuesStatusEnums.CANCEL.getCode());

        LambdaUpdateWrapper<DuesOrder> duesOrderLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        duesOrderLambdaUpdateWrapper.set(DuesOrder::getPaid, DuesStatusEnums.CANCEL.getCode());
        duesOrderLambdaUpdateWrapper.set(DuesOrder::getUpdateTime, LocalDateTime.now());
        duesOrderLambdaUpdateWrapper.eq(DuesOrder::getId, duesOrder.getId());
        duesOrderMapper.update(null, duesOrderLambdaUpdateWrapper);
        return true;
    }
}
